package com.webserver.core;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DispatcherServlet {
    public void service (HttpRequest request,HttpResponse response){
        String path = request.getUrl();
        File file = new File("./webapps"+path);
        response.setEntity(file);
        Map<String,String> mimeMapping = new HashMap<>();
        SAXReader reader = new SAXReader();

        if(file.exists()&&file.isFile()){
           try {
                Document doc = reader.read("./config/web.xml");
                Element root = doc.getRootElement();
                List<Element>list = root.elements("mime-mapping");
                for(Element e : list){
                    String key = e.elementText("extension");
                    String value = e.elementText("mime-type");
                    mimeMapping.put(key,value);
                }
                response.addHeader("Content-Type",mimeMapping.get(file.getName().substring(file.getName().lastIndexOf(".")+1)));
                response.addHeader("Content-Length",file.length()+"");
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }else{
            response.setStatusCode(404);
            response.setStatusReason("NOtFound");
            file = new File("./webapps/root/404.html");
            response.setEntity(file);
            response.addHeader("COntent-TYpe",mimeMapping.get(file));
            response.addHeader("Content-Length",file.length()+"");
        }
        response.addHeader("Server","WebServer");
    }
}
